import subprocess
import sys
import re
import os

#import base64
#import mimetypes
#import smtplib
#import errno

import base64
import mimetypes
import smtplib

import errno
#import winsound
import platform

import codecs

from EMLsqlite import Database




def to_unicode_or_bust(obj, encoding='iso_8859_1'):
        if isinstance(obj, basestring):
                if not isinstance(obj, unicode):
                        obj = unicode(obj, encoding)
        return obj

class DirWalker(object):

        def walk(self,dir,meth):
                """ walks a directory, and executes a callback on each file """
                dir = os.path.abspath(dir)
                #print "dir absolute path= %s " % dir
                for file in [file for file in os.listdir(dir) if not file in [".",".."]]:
                        
                        try:
                          
                          dir = to_unicode_or_bust(dir)
                          file = to_unicode_or_bust(file)

                          #print "\n\n      file= %s " % file
                          nfile = os.path.join(dir,file)
                          
                          #print "WORKING WITH %s " % nfile
                          if os.path.isfile(nfile):
                            #print "------ IS FILE "
                            meth(nfile)
                          elif os.path.isdir(nfile):
                            #print "------ IS DIR "
                            self.walk(nfile,meth)
                        except:
                          print "exception handling %s" % file

def mkdirRecursivo(directorio):
        aux = []
        while (not os.path.exists(directorio)):
                #print "el directorio %s no existe" % directorio
                aux.append(directorio)
                directorio = os.path.dirname(directorio)
                #print "directorios a crear: %d " % len(aux)

        
        aux.reverse()
        
        for eldir in aux:
                try:
                        os.mkdir(eldir)
                except Exception, e:
                        print "error creando directorio %s error %s " % (eldir,e)
                        




def convert_pst_to_mbox(pstfilename):
    global outputfolder
    global options
    
    if (options != 'M' or options != 'S'):
      options = 'M'
    
    #parent folder output
    try:
            if (not os.path.exists(outputfolder)):
                    #print "llamando a mkdir para %s " % dirdestino
                    mkdirRecursivo(outputfolder)
    except OSError, e:
            # Ignore directory exists error
            if e.errno != errno.EEXIST:
                    raise


    #pst file folder 
    dircreado = outputfolder
    try:
      

            #print "--------------------------------------------------------abspath %s " % os.path.abspath(pstfilename)
            #print "--------------------------------------------------------basename %s " % os.path.basename(pstfilename)
            #print "--------------------------------------------------------dirname %s " % os.path.dirname(pstfilename)

            pstfilemod = os.path.basename(pstfilename)
            pstfilemod = pstfilemod.replace('.','_')
            dircreado = os.path.join(outputfolder,pstfilemod)
            #print "--------------------------------------------------------pstfilename %s " % pstfilename
            #print "--------------------------------------------------------pstfilemod %s " % pstfilemod
            #print "--------------------------------------------------------outputfolder %s " % outputfolder
            #print "--------------------------------------------------------llamando a mkdir para %s " % dircreado
            if (not os.path.exists(dircreado)):
                    print "--------------------------------------------------------llamando a mkdir para %s " % dircreado
                    mkdirRecursivo(dircreado)
    except OSError, e:
            # Ignore directory exists error
            if e.errno != errno.EEXIST:
                    raise
    
    

    (shortname, extension) = os.path.splitext(pstfilename) 
    if (extension == '.pst' or extension == '.ost'):
      subprocess.call(['readpst','-' + options, '-o', dircreado,  pstfilename])
     

	
def rellenarCorreoBD(filepath):
	"""guardar en la bd en files el adjunto actual i su padre"""
	global databasename

	
	db = Database(databasename)
	
	try:
		lastidfile = db.get_id_file(filepath)
		if (lastidfile == -1):
			lastidfile = db.add_file(filepath)
		else:
			raise
		print "[rellenarCorreoBD ] insertado %s " % filepath
		db.close()
	except Exception, e:
		db.close()
		print "[rellenarCorreoBD ] error:%s con  %s " %   (e,filepath)
		

#  --------------------------------------------------bd work ----------------------------------------------------------
def dbWork ( dirdest,dbname):

  global dirdestino
  global outputfolder
  global databasename
  

  outputfolder = dirdest
  dirdestino = dirdest
   #dbname
  databasename = os.path.abspath(dirdestino) + '/' + dbname
  if (not databasename.endswith('.db')):
	databasename = databasename + '.db'

  print "[dbWord - EMLextractor] creando base de datos..."

  try:
    db = Database(databasename)
    db.initDatabase()
    db.close()
    print "[dbWord - EMLextractor] base de datos creada!"
  except Exception, e:
    print "[dbWord - EMLextractor]1 create database %s " % e

  
  
  pathwalker = DirWalker()
  pathwalker.walk(dirdest,rellenarCorreoBD)


#-----------------------------------------------------module--main-----------------------------------------------------        
def moduleMain (target, dirdest, typeextraction):
  global options
  global outputfolder
  
  options = typeextraction
  outputfolder = dirdest
  
  pathwalker = DirWalker()
  pathwalker.walk(target,convert_pst_to_mbox)
  
  
#-----------------------------------------------------script--main-----------------------------------------------------
if __name__ == "__main__":
  outputfolder = 'output'
  target = os.curdir
  options = "M"
  if len(sys.argv) < 3:
      sys.stderr.write('Usage: EMLextractor.py <opciones de extraccion M o S> <directorio_psts> <directorio_destino> ')
      sys.exit(1)
  else:
      target = sys.argv[2]
      outputfolder = sys.argv[3]
      options = sys.argv[1]




  pathwalker = DirWalker()
  pathwalker.walk(target,convert_pst_to_mbox)




